/* 
 * This javascript represents the Facualty Function 
 * Author : Kun.Huang
 * Create Data: 19/5/2013
 * LastUpdate :9/6/2013
 * */
function Controller_Faculty()
{
    this.Name = "Controller_Faculty";

    /**
     * Auto communication with server
     * @returns {undefined}
     */
    this.autoGetUpdatesFromServer = function()
    {
        var checkmsg = function()
        {
            CPS.sendRequestToServer("CPS_CheckServerNotification", [CPS.getUserID()], function(data) {
                var len = data.Response_CarriedData.length;
                if (len < 1)
                {
                    return;
                }
                // show the message
                for (var i = 0; i < len; i++) {
                    CPS.showNotification("(" + (i + 1) + "):" + data.Response_CarriedData[i].MessageTitle, data.Response_CarriedData[i].MessageContent, 2, 40000);
                }
                eval("currentController.initLeftBar();");
            });
        };
        window.setInterval(checkmsg, 3000);
    };

    /**
     * init the leftbar
     * @returns {undefined}
     */
    this.initLeftBar = function()
    {
        var parentContainerSelector = "#Index_West";
        var btnHtml = "<div id='Accordion_Left'></div><br/>";
        btnHtml += "<a href='javascript:void(0) 'id='Btn_NewApplication' onClick='currentController.createNewApplication();'>Creare New Application</a>";
        btnHtml += "<br><br><a href='javascript:void(0) 'id='Btn_searchApplication' onClick='currentController.search();'>Search Application</a>";
        $(parentContainerSelector).panel({content: btnHtml});
        var btnCreateNewSelector = String.format("{0} {1}", parentContainerSelector, " #Btn_NewApplication");
        var btnSearchSelector = String.format("{0} {1}", parentContainerSelector, " #Btn_searchApplication");
        $(btnCreateNewSelector).linkbutton({
            iconCls: 'icon-add'
        });
        $(btnSearchSelector).linkbutton({
            iconCls: 'icon-search'
        });

        var accordionSelector = String.format("{0} {1}", parentContainerSelector, " #Accordion_Left");
        $(accordionSelector).accordion({animate: true}); // init the accordinon

        CPS.sendRequestToServer("Faculty_QuerySummary", null, function(response) {
            // Step 1:  load the pannel sumary,here create the panel, contribute the title of the accordan
            var title = "{0}-({1})";
            for (var id in response.Response_CarriedData)
            {
                $(accordionSelector).accordion('add', {
                    title: String.format(title, response.Response_CarriedData[id].HandleSchoolName, response.Response_CarriedData[id].TotalCount),
                    id: response.Response_CarriedData[id].HandleSchoolID,
                    collapsible: true,
                    selected: false
                });
            }
            //bind the selet event
            $(accordionSelector).accordion({
                onSelect: function(title, index) {
                    var selectedSchoolId = $(accordionSelector).accordion('getPanel', index).panel("options").id;
                    CPS.sendRequestToServer("Faculty_QuerySummaryDetail", [selectedSchoolId], function(data) {
                        var objData = data.Response_CarriedData;
                        Trace.debugJsObjectData(objData);
                        var innerHtml = "<table style='min-width:100px'>";
                        for (var id in objData) {
                            var appTypeId = objData[id].ApplicationTypeID;
                            var appTypeName = objData[id].ApplicationTypeName;
                            var schoolID = objData[id].SchoolID;
                            var schoolName = objData[id].HandleSchoolName;
                            var count = objData[id].RecordCount;
                            innerHtml += String.format("<tr><td>{0}</td>", appTypeName);
                            var strShowDetialHtml = "<td style='text-align:right'>[<a href='#' onClick='currentController.ViewAccordionDetail(\"{0}\",\"{1}\",\"{2}\",\"{3}\")'>{4}</a>]</td></tr>";
                            innerHtml += String.format(strShowDetialHtml, schoolID, schoolName, appTypeId, appTypeName, count);
                        }
                        innerHtml += "</table>";
                        // set the property using pannel method, renew the contenet of each panel
                        $(accordionSelector).accordion('getPanel', index).panel({
                            collapsible: true,
                            content: innerHtml
                        });

                    });

                }
            });
        });
    };



    /**
     * Create a new application
     * @returns {undefined}
     */
    this.createNewApplication = function()
    {
        var html = "<table id='Div_CreateNewApplication'>";
        html += "<tr>";
        html += "<td>Application Type";
        html += "</td>";
        html += "<td>";
        html += "<input type='text' name='Application_Type' id='Application_Type' style='width:200px;' />";
        html += "</td>";
        html += "<td rowspan='6' style='vertical-align: top'>";
        html += "<div id='UploadFile_DIV' style ='max-height: 260px; overflow-y: scroll'>";
        html += "<a id='Btn_AddUploadFileBlock'>Btn_AddUploadFileBlock</a>";
        html += "</div>";
        html += "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>";
        html += "HandleSchool";
        html += "</td>";
        html += "<td>        ";
        html += "<input type='text' name='Application_HandleSchool' id='Application_HandleSchool' style='width:200px;' />";
        html += "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>";
        html += "Applicant Name";
        html += "</td>";
        html += "<td>";
        html += "<input type='text' name='Refference_Name' id='Refference_Name' style='width:200px;' />";
        html += "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>";
        html += "Applicant ID";
        html += "</td>";
        html += "<td>";
        html += "<input type='text' name='Refference_ID' id='Refference_ID' style='width:200px;' />";
        html += "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>";
        html += "ID Type";
        html += "</td>";
        html += "<td>";
        html += "<input type='text' name='Refference_Type' id='Refference_Type' style='width:200px;'/>";
        html += "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>Application Comment</td>";
        html += "<td>";
        html += "<textarea  wrap='physical' id='Refference_Comment' style='resize:none;height:100px;width:200px;border: 1px #000 solid'></textarea>";
        html += "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td colspan='3' style='text-align: center'>";
        html += "<a id='Btn_CreateNewApplication'>Btn_CreateNewApplication</a>";
        html += "</td>";
        html += "</tr>";
        html += "</table>";

        var containerID = CPS.addnewTab("Create New Application").innerDivID;
        var containerSelector = "#" + containerID;
        $(containerSelector).html("").append(html);
        // Item 01: Handel Application Type
        var Selector_AppType = String.format("{0} {1}", containerSelector, "#Application_Type");
        $(Selector_AppType).combobox({
            required: true,
            editable: false,
            valueField: 'Item_Key',
            textField: 'Item_Value',
            onBeforeLoad: function()
            {
                CPS.sendRequestToServer("GetApplicationTypeConfig", null, function(data) {
                    $(Selector_AppType).combobox('loadData', data);
                });
            }
        });
        // Item 02： deal with the schools
        var Selector_HandleSchool = String.format("{0} {1}", containerSelector, "#Application_HandleSchool");
        $(Selector_HandleSchool).combobox({
            required: true,
            multiple: true,
            editable: false,
            valueField: 'Item_Key',
            textField: 'Item_Value',
            onBeforeLoad: function()
            {
                CPS.sendRequestToServer("GetSchoolConfig", null, function(data) {
                    $(Selector_HandleSchool).combobox('loadData', data);
                });
            }
        });
        // Item03 refference Name
        var Selector_RefferenceName = String.format("{0} {1}", containerSelector, "#Refference_Name");
        $(Selector_RefferenceName).validatebox({
            required: true,
            missingMessage: 'Must input the ApplicationName'
        });
        // Item 04 refference ID
        var Selector_RefferenceID = String.format("{0} {1}", containerSelector, "#Refference_ID");
        $(Selector_RefferenceID).validatebox({
            required: true
        });
        // Item 05 refference Type
        var Selector_RefferenceType = String.format("{0} {1}", containerSelector, "#Refference_Type");
        $(Selector_RefferenceType).combobox({
            required: true,
            editable: false,
            valueField: 'Item_Key',
            textField: 'Item_Value',
            onBeforeLoad: function()
            {
                CPS.sendRequestToServer("GetReferenceTypeConfig", null, function(data) {
                    $(Selector_RefferenceType).combobox('loadData', data);
                });
            }
        });
        // Item 06 Refference_Comment
        var Selector_RefferenceComment = String.format("{0} {1}", containerSelector, "#Refference_Comment");
        $(Selector_RefferenceComment).validatebox({
            required: true
        });
        //--------------------------------
        //File Upload from Here
        //--------------------------------
        var Selector_FileUploadContainer = String.format("{0} {1}", containerSelector, "#UploadFile_DIV");
        var Selector_Btn_CreateNewUploadBlock = String.format("{0} {1}", Selector_FileUploadContainer, "#Btn_AddUploadFileBlock");
        // all created block selector
        var Selector_All_Blocks = Selector_FileUploadContainer + " table[name*=\"FileToUpLoadBlock_\"]";
        // register add new upload block button
        $(Selector_Btn_CreateNewUploadBlock).linkbutton({
            iconCls: 'icon-save',
            iconAlign: 'left',
            text: 'Add A File to Upload'
        }).click(function() {
            FileUpload.AddNew(Selector_FileUploadContainer);
        });
        //---------------
        // the submit button works here    
        // init the sent button
        var Selector_Submit = String.format("{0} {1}", containerSelector, "#Btn_CreateNewApplication");
        $(Selector_Submit).linkbutton({
            iconCls: 'icon-save',
            iconAlign: 'left',
            text: 'Submit'
        }).click(function() {
            CPS.confirmAction("Confirm", "Do you want to add this Application", function() {
                var bValid = true;
                bValid = bValid && $(Selector_AppType).combobox('isValid');
                bValid = bValid && $(Selector_HandleSchool).combobox('isValid');
                bValid = bValid && $(Selector_RefferenceName).validatebox('isValid');
                bValid = bValid && $(Selector_RefferenceID).validatebox('isValid');
                bValid = bValid && $(Selector_RefferenceType).combobox('isValid');
                bValid = bValid && $(Selector_RefferenceComment).validatebox('isValid');
                //check the select file
                var fileList = new Array();
                $(Selector_All_Blocks).each(function(index, element) {
                    var Selector_FileStatus = Selector_FileUploadContainer + " #" + element.id + " #File_State";
                    var Selector_FileID = Selector_FileUploadContainer + " #" + element.id + " #File_ServerMd5";
                    var Selector_FileName = Selector_FileUploadContainer + " #" + element.id + " #Lable_FileName";
                    if ($(Selector_FileStatus).val() === "true")
                    {
                        var objFileInfo = {};
                        objFileInfo.FileID = $(Selector_FileID).val();
                        objFileInfo.FileName = $(Selector_FileName).html();
                        fileList.push(String.format("{0}|{1}", objFileInfo.FileID, objFileInfo.FileName));
                    }
                });
                // check the general input
                if (!bValid) {
                    CPS.showNotification("Error Input", "Error input field in Submit form");
                    return;
                }
                // check whether the length
                var handleSchoolLength = $(Selector_HandleSchool).combobox('getValues').length;
                if (handleSchoolLength > 2)
                {
                    CPS.showNotification(String.format("Error in select {0} Handle School", handleSchoolLength), "the maximun of select School is 2");
                    return;
                }
                // Admission
                if (handleSchoolLength > 1 && $(Selector_AppType).combobox('getValue') !== 'AppType02')
                {
                    CPS.showNotification(String.format("Error in select {0} Handle School", handleSchoolLength), "the maximum of selected School is 1 for transfer");
                    return;
                }
                if (fileList.length < 1)
                {
                    CPS.showNotification("File Submit Error", "Please Submit at lease File");
                    return;
                }
                CPS.ShowProcessing();
                //contribute the data object 
                var objData = new Model_CreateApplication();
                objData.ApplicationTypeID = $(Selector_AppType).combobox('getValue');
                objData.ApplicationHandleSchoolIDs = $(Selector_HandleSchool).combobox('getValues').join("|");
                objData.RefferenceName = $(Selector_RefferenceName).val().toString();
                objData.RefferenceID = $(Selector_RefferenceID).val();
                objData.RefferenceTypeID = $(Selector_RefferenceType).combobox('getValue');
                objData.ApplicationComment = $(Selector_RefferenceComment).val();
                objData.FileList = fileList.join("|");

                // Send to Server 
                CPS.sendRequestToServer("Faculty_CreateNewApplication", objData, function(data)
                {
                    CPS.CloseProcessing(function()
                    {
                        //close tab
                        $('#MainContent').tabs('close', "Create New Application");
                        eval("currentController.initLeftBar();");
                        CPS.showNotification("sucess,", "create application sucess");

                    });


                });
            });


        });

    };

    //---Advanced Search Function-------------

    this.search = function() {
        var selectedPanel = CPS.addnewTab("Search Application");
        var panelSelector = "#" + selectedPanel.innerDivID;
        $(panelSelector).html("");   // remove the old one

        $(panelSelector).append("<div id = \"search\"></div><div id=\"searchResultContainer\"> <div id = \"searchResultTable\"></div></div>");
        var searchSelector = String.format("{0} {1}", panelSelector, "#search");
        $(searchSelector).append("<input id =\"referenceTypeCombo\"><input id ='referenceText'><a id =\"searchBtn\" href ='#' class='easyui-linkbutton' data-option = \"iconCls:'icon-search' \">");

        var referenceComboSelector = String.format("{0} {1} {2}", panelSelector, "#search", "#referenceTypeCombo");
        $(referenceComboSelector).combobox({
            //  required: true,
            editable: false,
            valueField: 'Item_Key',
            textField: 'Item_Value',
            onBeforeLoad: function()
            {
                CPS.sendRequestToServer("GetReferenceTypeConfig", null, function(data) {
                    $('#referenceTypeCombo').combobox('loadData', data);
                    $(referenceComboSelector).combobox('select', 'RefferenceType02');
                });
            }
        });

        var referenceTextSelector = String.format("{0} {1} {2}", panelSelector, "#search", "#referenceText");
        var resultDisplaySelector = String.format("{0} {1} {2}", panelSelector, "#searchResultContainer", "#searchResultTable");
        var html = "<table class = 'HtmlFrame'>";
        html += "<tr><td>{0}</td></tr>";
        html += "<tr><td>{1}</td></tr>";
        html += "<tr><td>{2}</td></tr>";
        html += "</table>";

        var html2 = "<table class = 'HtmlFrame'>";
        html2 += "<tr><td>{0}</td></tr>";
        html2 += "<tr><td>{1}</td></tr>";
        html2 += "<tr><td>{2}</td></tr>";
        html2 += "<tr><td><hr></td></tr>";
        html2 += "<tr><td>{3}</td></tr>";
        html2 += "<tr><td>{4}</td></tr>";
        html2 += "</table>";
        var basicInfoHtmlFormatter = function(Obj) {
            var ApplicantID = Obj[0].RefferenceUserID;
            var StudentName = Obj[0].RefferenceUserName;
            var ApplicationTypeName = Obj[0].ApplicationTypeName;
            var basicInfoHtml = "<table class = \"basicInfoTalbe\" >";
            basicInfoHtml += "<tr><th>ApplicantID:</th><td>{0}</td><th>Student\&nbsp\Name: </th><td>{1}</td><th>ApplicationType:</th><td>{2}</td></tr></table>";
            basicInfoHtml = String.format(basicInfoHtml, ApplicantID, StudentName, ApplicationTypeName);
            return basicInfoHtml;
        };

        var ActionListHtmlFormatter = function(dataAL) {
            var ObjAL = dataAL.Response_CarriedData;
            var latestState = ObjAL[ObjAL.length - 1].NewStateID;
            var SchoolAndHistoryHtml = "<table class = 'SchoolAndActionStyle'><tr><td>{0}</td></tr>";
            SchoolAndHistoryHtml += "<tr><td>{1}</td></tr></table>";
            var SchoolHtml = "";
            var HandleSchoolName = ObjAL[0].HandleSchoolName;
            SchoolHtml += "<table class ='SchoolStyle'><tr><th>School</th><td>{0}</td><th class = 'even'>Latest Status</th><td>{1}</td></tr></table>";
            SchoolHtml = String.format(SchoolHtml, HandleSchoolName, latestState);
            var counter = 1;
            var ActionListHtml = "<table class ='ActionStyle'><tr><th>Index</th><th>Action</th><th>Action User</th><th>Date</th><th colspan=\"2\">Comment</th></tr>";
            // build the list
            var ObjAL = dataAL.Response_CarriedData;
            for (var id in ObjAL) {
                var ActionUserName = ObjAL[id].ActionUserName;
                var StateID = ObjAL[id].NewStateID;
                var date = ObjAL[id].CreatedTime;
                var Comment = ObjAL[id].NewStateComment;

                ActionListHtml += "<tr onmouseover=\"this.style.backgroundColor='#b5cfd2';\" onmouseout=\"this.style.backgroundColor='#ffffff';\">";
                ActionListHtml += "<td style = 'text-align:center'>{0}</td><td>{1}</td><td>{2}</td>";
                ActionListHtml += "<td>{3}</td><td colspan = \"2\" style='text-align:left;'>{4}</td></tr>";
                ActionListHtml = String.format(ActionListHtml, counter, StateID, ActionUserName, date, Comment);
                counter += 1;
            }
            ActionListHtml += "</table>";
            SchoolAndHistoryHtml = String.format(SchoolAndHistoryHtml, SchoolHtml, ActionListHtml);
            return SchoolAndHistoryHtml;
        };


        var FileListHtmlFormatter = function(fileData) {
            var counter = 1;
            var fileListHtml = "<table class = 'fileTH'><th>File Index</th><th colspan =\"2\">File Name</th><th>Upload User</th><th>Upload Time</th>";
            for (var id in fileData.Response_CarriedData) {
                var FileID = fileData.Response_CarriedData[id].FileID;
                var FileName = fileData.Response_CarriedData[id].FileName;
                var UserName = fileData.Response_CarriedData[id].UserName;
                var UserEmail = fileData.Response_CarriedData[id].UserEmail;
                var FileUploadTime = fileData.Response_CarriedData[id].FileUploadTime;
                fileListHtml += "<tr onmouseover=\"this.style.backgroundColor='#ffff66';\" onmouseout=\"this.style.backgroundColor='#ffffff';\">"; // [0] counter index
                // [1] fileID [2]=SID [3]= File Name
                fileListHtml += "<td style = 'text-align:center'>{0}</td><td colspan =\"2\">";
                fileListHtml += "<a target='_blank' href=\"../Server/server.php?ActionName=FileDownload&FileID={1}&SID={2}\">{3}</a></td>";
                fileListHtml = String.format(fileListHtml, counter, FileID, CPS.getSessionID(), FileName);
                //[4] userName [5] Upload Time
                var nameHtml = "<td><a href = 'javascript:void(0);'onclick = 'Mailer.Application_SendEmailByClickingName(\"{0}\",\"{1}\",\"{2}\",\"{3}\");'>";
                fileListHtml += String.format(nameHtml, UserName, UserEmail, CPS.getUserName(), CPS.getUserEmail());
                fileListHtml += "{0}</a></td><td>{1}</td></tr>";
                //fileTableHtml = String.format(fileTableHtml, FileID, FileName, UserName, Role, counter, CPS.getSessionID());
                fileListHtml = String.format(fileListHtml, UserName, FileUploadTime);
                counter = counter + 1;
            }
            fileListHtml += "</table>";
            return fileListHtml;
        };


        // the do search button
        var searchBtnSelector = String.format("{0} {1} {2}", panelSelector, "#search", "#searchBtn");
        $(searchBtnSelector).linkbutton({
            iconCls: 'icon-search'
        }).click(function() {

            // do the validation
            $(referenceTextSelector).validatebox({
                required: true
            });

            if ($(referenceTextSelector).validatebox('isValid')) {
                CPS.ShowProcessing();
                var referType = $(referenceComboSelector).combobox('getValue');
                var referID = $(referenceTextSelector).val();
                //
                CPS.sendRequestToServer("CPS_searchApplicationSchoolList", [referType, referID], function(data) {
                    Trace.debugJsObjectData(data.Response_CarriedData, "#369");
                    var size = data.Response_CarriedData.length;
                    if (size < 1)
                    {
                        CPS.CloseProcessing(function() {
                            CPS.showNotification("Search Result", "No Result Found");
                        });
                        return;
                    }
                    var basicInfo_Html = basicInfoHtmlFormatter(data.Response_CarriedData);
                    var ApplicationID = data.Response_CarriedData[0].ApplicationID;
                    var HandleSchoolID = data.Response_CarriedData[0].HandleSchoolID;

                    if (size === 2) {
                        var HandleSchoolID2 = data.Response_CarriedData[1].HandleSchoolID;
                        CPS.sendRequestToServer("CPS_searchApplicationActionList", [ApplicationID, HandleSchoolID], function(dataAL) {
                            Trace.debugJsObjectData(dataAL.Response_CarriedData, "#369");
                            var ActionList_Html = ActionListHtmlFormatter(dataAL);


                            CPS.sendRequestToServer("CPS_QueryFileList", [ApplicationID, HandleSchoolID], function(fileData) {
                                var fileList_Html = FileListHtmlFormatter(fileData);

                                ////////////////////////////////////////////////////////////
                                CPS.sendRequestToServer("CPS_searchApplicationActionList", [ApplicationID, HandleSchoolID2], function(dataAL) {
                                    Trace.debugJsObjectData(dataAL.Response_CarriedData, "#369");
                                    var ActionList_Html2 = ActionListHtmlFormatter(dataAL);
                                    CPS.sendRequestToServer("CPS_QueryFileList", [ApplicationID, HandleSchoolID2], function(fileData) {

                                        var fileList_Html2 = FileListHtmlFormatter(fileData);
                                        html2 = String.format(html2, basicInfo_Html, ActionList_Html, fileList_Html, ActionList_Html2, fileList_Html2);
                                        $(resultDisplaySelector).html(html2);
                                        CPS.CloseProcessing(function() {

                                        });

                                    });
                                });
                            });
                        });
                    } else {
                        CPS.sendRequestToServer("CPS_searchApplicationActionList", [ApplicationID, HandleSchoolID], function(dataAL) {
                            Trace.debugJsObjectData(dataAL.Response_CarriedData, "#369");
                            var ActionList_Html = ActionListHtmlFormatter(dataAL);
                            CPS.sendRequestToServer("CPS_QueryFileList", [ApplicationID, HandleSchoolID], function(fileData) {

                                var fileList_Html = FileListHtmlFormatter(fileData);

                                resultDisplaySelector = String.format("{0} {1} {2}", panelSelector, "#searchResultContainer", "#searchResultTable");
                                html = String.format(html, basicInfo_Html, ActionList_Html, fileList_Html);
                                $(resultDisplaySelector).html(html);
                                CPS.CloseProcessing(function() {
                                });
                            });
                        });
                    }
                });
            }
            // if not validated input
            else {
                CPS.showNotification("Wrong input", "Please input information before search!");
            }
        });
    };


    //----------End Search Function
    //---------------------------------------------------------

    /**
     * View the detail of the accordion 
     * @param {type} schoolID
     * @param {type} schoolName
     * @param {type} appTypeId
     * @param {type} appTypeName
     * @returns {undefined}
     */
    this.ViewAccordionDetail = function(schoolID, schoolName, appTypeId, appTypeName)
    {
        CPS.ShowProcessing();
        var title = String.format("{0}-[{1}]", schoolName, appTypeName);
        var selectedPanel = CPS.addnewTab(title);
        var panelSelector = "#" + selectedPanel.innerDivID;
        $(panelSelector).html("");   // remove the old one
        var strAction = "ViewAccordionDetail|{0}|{1}|{2}|{3}";
        strAction = String.format(strAction, schoolID, schoolName, appTypeId, appTypeName);
        // set to the hidden action value    
        $(selectedPanel.paramSelector).val(strAction);

        var rowFormatter = function(value, rowData, rowindex) {
            var currentStatus = rowData.ApplicationStateID;
            if (currentStatus === "F04") {
                var html = "<button id='Item_Btn_AddFile'onClick ='currentController.Application_Item_AddFile(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\");'>Add File</button>";
                html = String.format(html, rowData.ApplicationId, rowData.HandleSchoolID, rowData.ApplicationStateID, rowData.ActionUserID, strAction);
                return html;
            }
            // Accept button
            if ((currentStatus === "A02") || (currentStatus === "A03")) {
                var html = "<button id='Item_Btn_Accept'onClick ='currentController.Application_Item_Accept(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\");'>Accept</button>";
                html = String.format(html, rowData.ApplicationId, rowData.HandleSchoolID, rowData.ApplicationStateID, rowData.ActionUserID, strAction);
                return html;
            }

            if (currentStatus === "F06") {
                var html = "<span id ='finishedText'>Finished</span>";
                return html;
            }
        };

        var fontStyler = function() {
            return "font-size:14px;";
        };

        var conditionStyler = function(value, row, index) {
            if (value > CPS.getSystemSetting("ElaspeDayAlarm")) {
                return 'color:red;font-size:18px;text-align:center;text;font-weight: bold;';
            } else
            {
                return 'font-size:14px;text-align:center';
            }
        };

        var header = [[
                {field: 'ApplicationId', title: 'ApplicationId', hidden: true},
                {field: 'ApplicationTypeID', title: 'ApplicationTypeID', hidden: true},
                {field: 'RefferenceTypeID', title: 'RefferenceTypeID', hidden: true},
                {field: 'LatestComment', title: 'LatestComment', hidden: true},
                {field: 'HandleSchoolID', title: 'HandleSchoolID', hidden: true},
                {field: 'HandleSchoolName', title: 'HandleSchoolName', hidden: true},
                {field: 'SecretaryID', title: 'SecretatyID', hidden: true},
                {field: 'SecretaryName', title: 'SecretatyName', hidden: true},
                {field: 'SecretaryEmail', title: 'SecretatyEmail', hidden: true},
                {field: 'AdvisorID', title: 'AdvisorID', hidden: true},
                {field: 'AdvisorName', title: 'AdvisorName', hidden: true},
                {field: 'AdvisorEmail', title: 'AdvisorEmail', hidden: true},
                {field: 'ActionUserID', title: 'ActionUserID', hidden: true},
                {field: 'ActionUserName', title: 'ActionUserName', hidden: true},
                {field: 'ActionUserEmail', title: 'ActionUserEmail', hidden: true},
                {field: 'SortIndex', title: 'SortIndex', hidden: true},
                {field: 'LastUpdateTime', title: 'LastUpdateTime', width: 90, hidden: true},
                // not hidden
                {field: 'ApplicationTypeName', title: 'Application Type', width: 106, sortable: true, styler: fontStyler},
                {field: 'RefferenceUserName', title: 'Student Name', width: 110, sortable: true, styler: fontStyler},
                {field: 'RefferenceUserID', title: 'Reference ID', width: 90, sortable: true, styler: fontStyler},
                {field: 'RefferenceTypeName', title: 'Reference Type', width: 100, sortable: true, styler: fontStyler},
                {field: 'ApplicationComment', title: 'Comment', width: 120, sortable: true, styler: function() {
                        return 'word-wrap: break-word;font-size:14px';
                    }},
                {field: 'ApplicationStateID', title: 'Status', width: 100, sortable: true, styler: fontStyler},
                {field: 'FirstCreatedTime', title: 'Date Created', width: 90, sortable: true, styler: fontStyler},
                {field: 'ElapsedDay', title: 'ElapsedDay', width: 90, sortable: true, styler: conditionStyler},
                {field: 'Action', title: 'Action', width: 110, formatter: rowFormatter}
            ]];

        // handle data
        var toArrayData = function(carriedData) {
            var rows = [];
            for (var i = 0; i < carriedData.length; i++) {
                rows.push({
                    ApplicationId: carriedData[i].ApplicationId,
                    ApplicationTypeID: carriedData[i].ApplicationTypeID,
                    ApplicationTypeName: carriedData[i].ApplicationTypeName,
                    RefferenceUserName: carriedData[i].RefferenceUserName,
                    RefferenceUserID: carriedData[i].RefferenceUserID,
                    RefferenceTypeID: carriedData[i].RefferenceTypeID,
                    RefferenceTypeName: carriedData[i].RefferenceTypeName,
                    ApplicationComment: carriedData[i].ApplicationComment,
                    LatestComment: carriedData[i].LatestComment,
                    ApplicationStateID: carriedData[i].ApplicationStateID,
                    HandleSchoolID: carriedData[i].HandleSchoolID,
                    HandleSchoolName: carriedData[i].HandleSchoolName,
                    SecretaryID: carriedData[i].SecretaryID,
                    SecretaryName: carriedData[i].SecretaryName,
                    SecretaryEmail: carriedData[i].SecretaryEmail,
                    AdvisorID: carriedData[i].AdvisorID,
                    AdvisorName: carriedData[i].AdvisorName,
                    AdvisorEmail: carriedData[i].AdvisorEmail,
                    ActionUserID: carriedData[i].ActionUserID,
                    ActionUserName: carriedData[i].ActionUserName,
                    ActionUserEmail: carriedData[i].ActionUserEmail,
                    SortIndex: carriedData[i].SortIndex,
                    LastUpdateTime: carriedData[i].LastUpdateTime,
                    FirstCreatedTime: carriedData[i].FirstCreatedTime,
                    ElapsedDay: carriedData[i].ElapsedDay
                });
            }
            return rows;
        };

        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        var fm = function(rowIndex, rowData) {
            var html = "<div id =\"Form_TableGridDetailView_{0}\"></div>";
            return String.format(html, rowIndex);
        };
        var detailViewEventhandler = function(rowIndex, rowData) {
            CPS.sendRequestToServer("CPS_QueryFileList", [rowData.ApplicationId, rowData.HandleSchoolID], function(objData) {
                var counter = 1;
                var fileTableHtml = "<table><th>File Index</th><th colspan =\"2\">File Name</th><th>Upload User</th><th>Upload Time</th>";
                for (var id in objData.Response_CarriedData) {
                    var FileID = objData.Response_CarriedData[id].FileID;
                    var FileName = objData.Response_CarriedData[id].FileName;
                    var UserName = objData.Response_CarriedData[id].UserName;
                    var UserEmail = objData.Response_CarriedData[id].UserEmail;
                    var FileUploadTime = objData.Response_CarriedData[id].FileUploadTime;
                    //FileDownload
                    fileTableHtml += "<tr><td style = 'text-align:center'>{0}</td><td colspan =\"2\">"; // [0] counter index
                    // [1] fileID [2]=SID [3]= File Name 
                    fileTableHtml += "<a target='_blank' href=\"../Server/server.php?ActionName=FileDownload&FileID={1}&SID={2}\">{3}</a></td>";
                    fileTableHtml = String.format(fileTableHtml, counter, FileID, CPS.getSessionID(), FileName);
                    //[4] userName [5] Upload Time
                    var nameHtml = "<td><a href = 'javascript:void(0);'onclick = 'Mailer.Application_SendEmailByClickingName(\"{0}\",\"{1}\",\"{2}\",\"{3}\");'>";
                    fileTableHtml += String.format(nameHtml, UserName, UserEmail, CPS.getUserName(), CPS.getUserEmail());
                    fileTableHtml += "{0}</a></td><td>{1}</td></tr>";
                    //fileTableHtml = String.format(fileTableHtml, FileID, FileName, UserName, Role, counter, CPS.getSessionID());
                    fileTableHtml = String.format(fileTableHtml, UserName, FileUploadTime);
                    counter += 1;
                }
                fileTableHtml += "</table>";

                var html = " <table class = \"detailviewTable\" style =\"border:1px solid #369\"><tr><th>From:</th>";
                var fromHtml = "<td><a href = 'javascript:void(0);'onclick = 'Mailer.Application_SendEmailByClickingName(\"{0}\",\"{1}\",\"{2}\",\"{3}\");'>";
                html += String.format(fromHtml, rowData.ActionUserName, rowData.ActionUserEmail, CPS.getUserName(), CPS.getUserEmail());
                html += "{0}</a></td><th>Last updated time:</th><td>{1}</td></tr><tr><th>Last comment:</th>";
                html += "<td colspan=\"3\">{2}</td></tr><tr><th>Secretary:</th>";
                html = String.format(html, rowData.ActionUserName, rowData.LastUpdateTime, rowData.LatestComment);
                var secretaryHtml = "<td><a href = 'javascript:void(0);'onclick = 'Mailer.Application_SendEmailByClickingName(\"{0}\",\"{1}\",\"{2}\",\"{3}\");'>";
                html += String.format(secretaryHtml, rowData.SecretaryName, rowData.SecretaryEmail, CPS.getUserName(), CPS.getUserEmail());
                html += "{0}</a></td><th>Advisor:</th>";
                html = String.format(html, rowData.SecretaryName);
                var advisorHtml = "<td><a href = 'javascript:void(0);'onclick = 'Mailer.Application_SendEmailByClickingName(\"{0}\",\"{1}\",\"{2}\",\"{3}\");'>";
                html += String.format(advisorHtml, rowData.AdvisorName, rowData.AdvisorEmail, CPS.getUserName(), CPS.getUserEmail());
                html += "{0}</a></td></tr><tr><th>School:</th><td colspan = \"2\">{1}</td>";
                html = String.format(html, rowData.AdvisorName, rowData.HandleSchoolName);
                var HistoryBtn = "<td style='text-align:right'><button id='viewDetailBtn' onClick ='currentController.Application_Item_ViewHistory(\"{0}\",\"{1}\");'>View history</button></td></tr><tr>";
                html += String.format(HistoryBtn, rowData.ApplicationId, rowData.HandleSchoolID);
                html += "<td colspan = \"4\" class = \"fileTH\" style='text-align: center;padding-left: 50px'><div id = \"TableGrid_UploadFileList\" style = 'overflow-y: scroll; max-height: 250px'>{0}</div></td></tr></table>";
                html = String.format(html, fileTableHtml);

                var expandSelector = String.format("{0} #Form_TableGridDetailView_{1}", panelSelector, rowIndex);
                $(expandSelector).panel({
                    content: html
                });
            });

        };



        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        CPS.sendRequestToServer("Faculty_QueryAccordionDetail", [schoolID, appTypeId], function(data) {
            Trace.debugJsObjectData(data.Response_CarriedData, "#369");
            DataGridComponent.Init(panelSelector, header);
            DataGridComponent.SetDetailviewWithExpandEvent(fm, detailViewEventhandler);
            DataGridComponent.LoadData(toArrayData(data.Response_CarriedData));
            CPS.CloseProcessing(function() {
            });
        });

    };

//-----------------------------------------------------------------------------------------------
// The below is the button action of eath application Item
//-----------------------------------------------------------------------------------------------
    this.Application_Item_ViewHistory = function(rowApplicationID, rowHandleSchoolID) {
        var ActionListHtmlFormatter = function(dataAL) {
            var ObjAL = dataAL.Response_CarriedData;
            var counter = 1;
            var ActionListHtml = "<table id ='HistoryDetailTable'><tr><th>Index</th><th>Action</th><th>Action User</th><th>Date</th><th colspan=\"2\">Comment</th></tr>";
            // build the list
            var ObjAL = dataAL.Response_CarriedData;
            for (var id in ObjAL) {
                var ActionUserName = ObjAL[id].ActionUserName;
                var StateID = ObjAL[id].NewStateID;
                var date = ObjAL[id].CreatedTime;
                var Comment = ObjAL[id].NewStateComment;

                ActionListHtml += "<tr onmouseover=\"this.style.backgroundColor='#b5cfd2';\" onmouseout=\"this.style.backgroundColor='#ffffff';\">";
                ActionListHtml += "<td style = 'text-align:center'>{0}</td><td>{1}</td><td>{2}</td>";
                ActionListHtml += "<td>{3}</td><td colspan = \"2\" style='text-align:left;'>{4}</td></tr>";
                ActionListHtml = String.format(ActionListHtml, counter, StateID, ActionUserName, date, Comment);
                counter += 1;
            }
            ActionListHtml += "</table>";
            return ActionListHtml;
        };

        CPS.sendRequestToServer("CPS_searchApplicationActionList", [rowApplicationID, rowHandleSchoolID], function(dataAL) {
            Trace.debugJsObjectData(dataAL.Response_CarriedData, "#369");
            var ActionList_Html = ActionListHtmlFormatter(dataAL);

            var tempDivSelector = "#" + CPS.AddTempDIV();
            CPS.ShowAsWindow(tempDivSelector, 600, 350, true);
            $(tempDivSelector).panel({
                title: "Application History Detail",
                content: ActionList_Html
            });

        });
    };

    this.Application_Item_Accept = function(rowApplicationID, rowHandleSchoolID, rowStateID, rowActionUserID, strCallbackAction) {
        CPS.confirmAction("Accept Confirmation", "confirm to Accept this Application?", function() {
            var actionEntity = new Action_Entity();
            actionEntity.rowApplicationID = rowApplicationID;
            actionEntity.rowHandleSchoolID = rowHandleSchoolID;
            actionEntity.rowStateID = rowStateID;
            actionEntity.rowActionUserID = rowActionUserID;
            actionEntity.newActionUserID = CPS.getUserID();
            if (actionEntity.rowStateID === "A02") {
                actionEntity.newActionStateID = "F04";
            }
            if (actionEntity.rowStateID === "A03") {
                actionEntity.newActionStateID = "F06";
            }
            actionEntity.callbackAction = strCallbackAction;
            //Send to Server
            CPS.sendRequestToServer("Faculty_AcceptApplication", actionEntity, function(data) {
                CPS.parseActionString(data.Response_ActionName);
                CPS.showNotification("Sucess", "The application has been accepted");
            });
        });
    };


    /**
     * Add file function
     * @param {type} rowApplicationID
     * @param {type} rowHandleSchoolID
     * @param {type} rowStateID
     * @param {type} rowActionUserID
     * @param {type} strCallback
     * @returns {undefined}
     */
    this.Application_Item_AddFile = function(rowApplicationID, rowHandleSchoolID, rowStateID, rowActionUserID, strCallback)
    {
        var html = "<div id=\"CommonUploadModule\" title=\"File Upload\">";
        html += "<table id = 'addFileWindow' style=\"margin-left: auto; margin-right: auto;\">";
        html += "<tr>";
        html += "<td colspan = '2' style='text-align: center;font-size: 20px'>Comment</td>";
        html += "</tr>";
        html += "<tr>                     ";
        html += "<td colspan=\"2\">";
        html += "<textarea wrap=\"physical\" id=\"Refference_Comment\" style=\"resize:none;height:80px;width:550px;border: 1px #000 solid\"></textarea>";
        html += "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td rowspan=\"2\" style=\"vertical-align: top\">";
        html += "<div id=\"UploadFile_DIV\">";
        html += "<a id=\"Btn_AddUploadFileBlock\">Btn_AddUploadFileBlock</a>";
        html += "</div>";
        html += "</td>";
        html += "<td style=\"text-align: right\">";
        html += "<a id=\"Btn_SubmitSupplementAction\">Upload Files</a>";
        html += "</td>";
        html += "</tr>";
        html += "</table>";
        html += "</div>";

        var divId = CPS.AddTempDIV();
        var containerSelector = String.format("#{0}", divId);
        var Selector_FileUploadContainer = String.format("{0} {1} {2}", containerSelector, '#CommonUploadModule', "#UploadFile_DIV");
        var Selector_Btn_CreateNewUploadBlock = String.format("{0} {1}", Selector_FileUploadContainer, "#Btn_AddUploadFileBlock");
        var fileList = null;
        // all created block selector
        var Selector_Submit = String.format("{0} {1}", containerSelector, "#Btn_SubmitSupplementAction");
        // load the HTML
        $(containerSelector).html(html);

        var commentSelector = String.format("{0} {1}", containerSelector, "#Refference_Comment");
        // regester the submit fucntion
        $(commentSelector).validatebox({
            required: true,
            title: "Add File for Advisor request"
        });

        // Submit button
        $(Selector_Submit).linkbutton({
            iconCls: 'icon-save',
            iconAlign: 'left',
            text: 'Submit'
        }).click(function() {
            fileList = FileUpload.Validate(Selector_FileUploadContainer);
            if (!$(commentSelector).validatebox('isValid'))
            {
                CPS.showNotification("Alert", "need to  input comments in Submit form");
                return;
            }
            if (fileList.length < 1)
            {
                CPS.showNotification("Alert", "need to  upload at lease one file");
                return;
            }

            var objSupplement = new Action_Entity();
            objSupplement.rowApplicationID = rowApplicationID;
            objSupplement.rowHandleSchoolID = rowHandleSchoolID;
            objSupplement.rowStateID = rowStateID;
            objSupplement.rowActionUserID = rowActionUserID;
            objSupplement.newActionUserID = CPS.getUserID();
            objSupplement.newActionStateID = "F05";
            objSupplement.newActionComment = $(commentSelector).val();
            objSupplement.FileList = fileList.join("|");
            objSupplement.callbackAction = strCallback;
            //Send to Server
            CPS.sendRequestToServer("Faculty_AddFiles", objSupplement, function(data) {
                $(containerSelector).window('close');
                CPS.parseActionString(data.Response_ActionName);
                CPS.showNotification("Sucess", "Successfully uploaded ");

            });


        });

        // register add new upload block button
        $(Selector_Btn_CreateNewUploadBlock).linkbutton({
            iconCls: 'icon-save',
            iconAlign: 'left',
            text: 'Add A File to Upload'
        }).click(function() {
            FileUpload.AddNew(Selector_FileUploadContainer);
        });

        CPS.ShowAsWindow(containerSelector, 600, 400, true);

    };


}
;